﻿using AutoMapper;
using B.S.GridManager.Api.Write.Application.Command.PhsicalGrid;
using B.S.GridManager.ErrorCode;
using B.S.GridManager.Infrastructure.Interface;
using B.S.GridManger.Domain.Entities;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.GridManager.Api.Write.Application.CommandHandler.PhsicalGrid
{
    public class CreatePhysicalGridHandler : IRequestHandler<CreatePhysicalGridCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<PhysicalGridModel> physicalGirdRepo;
        private readonly IMapper mapper;
        private readonly ILogger<CreatePhysicalGridHandler> logger;
        /// <summary>
        /// 添加物理网格的处理方法
        /// </summary>
        /// <param name="physicalGirdRepo">物理网格仓储对象</param>
        /// <param name="mapper">对象映射工具</param>
        /// <param name="logger">日志对象</param>
        public CreatePhysicalGridHandler(IBaseRepository<PhysicalGridModel> physicalGirdRepo,IMapper mapper,ILogger<CreatePhysicalGridHandler> logger)
        {
            this.physicalGirdRepo = physicalGirdRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        public Task<ApiResult<int>> Handle(CreatePhysicalGridCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            PhysicalGridModel model = mapper.Map<PhysicalGridModel>(request);
            model.Id = YitIdHelper.NextId();
            model.CreateName = "admin";
            model.CreateTime = DateTime.Now;

            int r = physicalGirdRepo.Create(model);
            if (r > 0)
            {
                result.Code = ApiEnums.Success;
                result.Msg = "添加成功!";
                result.Data = r;
            }
            else {
                result.Code = ApiEnums.Fail;
                result.Msg = "添加失败!";
                result.Data = r;
            }

            return Task.FromResult(result);

        }
    }
}
